import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:math';
import 'GlobalSeer.dart';

class MyUDP{

  late RawDatagramSocket _socket;

  void connect() async{
    RawDatagramSocket.bind("192.168.3.16", 3001).then((socket) {
      print("socket done!");
      _socket=socket;
      _socket.broadcastEnabled=true;
      _socket.listen((RawSocketEvent event){
        if (event == RawSocketEvent.read) {
          final datagram = _socket.receive();
          if (datagram != null) {
            String message = utf8.decode(datagram.data);
            print("message:$message");
          }
        }
      });
    },
    onError: (e){
      print(e.toString());
    });
  }

  void send(String str){
    if(_socket!=null){
      _socket.send(utf8.encode(str), InternetAddress("192.168.3.6"), 4532);
    }
  }

}

main(){
  runApp(TheApp());
}

class TheApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(home: MyHome(),);
  }
}

class MyHome extends StatelessWidget{

  MyUDP _udp=MyUDP();

  @override
  Widget build(BuildContext context){

    GlobalSeer.addEventListener("onDialogDone", (device){
      print("device.id:");
    });

    return Scaffold(
      appBar: AppBar(title:const Text("UDP"),centerTitle: true,backgroundColor: Colors.purple,),
      body:Center(
        child:Column(
          children:[
            const SizedBox(height: 50,),
            ElevatedButton(onPressed: (){
              _udp.connect();
            }, child: const Text("CONNECT")),
            const SizedBox(height: 50,),
            Text("deciceName:"),
            const SizedBox(height: 50,),
            ElevatedButton(onPressed: (){
              _udp.send("pig123");
            }, child: const Text("SEND")),
          ],
        ) ,
      ),

    );
  }

}

